from django.conf import settings
from rest_framework import serializers
from utils.serializersfield import DelayTimeCharField
from apps.member.models import MemberRecord
from apps.member.serializers import MemberInfoSerializer
from apps.member.comment.models import Comment
from .models import Diary


class DiaryDetailSerializer(serializers.ModelSerializer):
    image = serializers.SerializerMethodField()
    is_like = serializers.SerializerMethodField()
    user_info = serializers.SerializerMethodField()
    create_time = DelayTimeCharField()
    model_name = serializers.SerializerMethodField()
    comment_count = serializers.SerializerMethodField()
    label = serializers.SerializerMethodField()

    def get_label(self, obj):
        if obj.label:
            return obj.label.split(',')
        return []

    def get_user_info(self, obj):
        return MemberInfoSerializer(instance=obj.user.member).data

    def get_model_name(self, obj):
        return 'Diary'.lower()

    def get_is_like(self, obj):
        user = self.context['request'].user
        if user.is_authenticated:
            member_record = MemberRecord.objects.filter(content_type=Diary.get_content_type(), object_id=obj.id,
                                                        user=user, operate=MemberRecord.LIKE).first()
            if member_record:
                return True
        return False

    def get_is_collect(self, obj):
        user = self.context['request'].user
        if user.is_authenticated:
            member_record = MemberRecord.objects.filter(content_type=Diary.get_content_type(), object_id=obj.id,
                                                        user=user, operate=MemberRecord.COLLECT).first()
            if member_record:
                return True
        return False

    def get_comment_count(self, obj):
        comments = Comment.objects.filter(content_type=Diary.get_content_type(), delete=False, object_id=obj.id)
        return comments.count()

    def get_image(self, obj):
        return settings.TENCENT_CLOUD['IMAGE_URL'] + obj.image.filepath

    class Meta:
        model = Diary
        fields = ('model_name', 'title', 'describe', 'user_info', 'id', 'image', 'is_like', 'content',
                  'create_time', 'browse_count', 'like_count', 'comment_count', 'label')
